<template>
  <el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForm"
    :rules="rules"
    label-width="auto"
    class="demo-ruleForm"
    :size="formSize"
    status-icon
  >
    <el-form-item
      v-if="actionType === 'update' || actionType === 'delete'"
      label="类别ID"
      prop="categoryId"
    >
      <el-input v-model="ruleForm.categoryId" disabled />
    </el-form-item>
    <el-form-item label="类别名称" prop="categoryName">
      <el-input
        v-model="ruleForm.categoryName"
        :disabled="actionType === 'delete'"
      />
    </el-form-item>
    <el-form-item>
      <el-button
        v-if="actionType !== 'delete'"
        type="primary"
        @click="submitForm(ruleFormRef)"
        >提交</el-button
      >
      <el-button
        v-if="actionType === 'delete'"
        type="danger"
        @click="handleDelete()"
        >删除</el-button
      >
      <el-button @click="close">关 闭</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { reactive, ref, watch } from "vue";
import {
  ElMessage,
  ElMessageBox,
  type ComponentSize,
  type FormInstance,
  type FormRules
} from "element-plus";
import type { CategoryDTO, CategoryForm } from "@/api/category";
import {
  getCategoryById,
  addCategory,
  updateCategory,
  deleteCategory
} from "@/api/category";

/** ------------------组件通信-接收数据-------------------- */

const emit = defineEmits(["close"]);
const props = defineProps({
  categoryId: {
    type: Number,
    default: null
  },
  action: {
    type: String,
    default: null
  }
});

watch(
  () => props.categoryId,
  (newValue, oldValue) => {
    if (newValue !== null) {
      initData(newValue);
    }
  },
  { deep: true, immediate: true }
);

/** ------------------加载初始化数据-------------------- */
const actionType = ref<string>();
function initData(_categoryId: number) {
  setTimeout(() => {
    actionType.value = props.action;
    getCategoryById(_categoryId).then(response => {
      ruleForm.value = response.data;
    });
  }, 200);
}

/** ------------------表单数据-------------------- */
// 表单属性size
const formSize = ref<ComponentSize>("default");
const ruleFormRef = ref<FormInstance>();
const ruleForm = ref<CategoryForm>({
  categoryId: 0,
  categoryName: "",
  createTime: undefined
});

//表单校验规则
const rules = reactive<FormRules<CategoryForm>>({
  categoryName: [
    { required: true, message: "类别名称不能为空", trigger: "change" }
  ]
});

/** 提交表单 */
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (props.categoryId !== null) {
        console.log(ruleForm.value);
        updateCategory(ruleForm.value).then(response => {
          ElMessage.success("更新类别成功");
          close();
        });
      } else {
        addCategory(ruleForm.value).then(response => {
          ElMessage.success("添加类别成功");
          close();
        });
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

/** 重置表单 */
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

function reset() {
  resetForm(ruleFormRef.value);
  actionType.value = undefined;
}

/** 关闭窗口 */
function close() {
  reset();
  emit("close");
}

/** 删除类别 */
function handleDelete() {
  const categoryId = ruleForm.value.categoryId || props.categoryId;
  ElMessageBox.confirm("是否删除编号为" + categoryId + "的数据?", "警告")
    .then(() => {
      return deleteCategory(categoryId);
    })
    .then(() => {
      close();
      ElMessage({ type: "success", message: "删除成功" });
    })
    .catch(() => {});
}
</script>
